package com.wuqi.dev.logindemo;

import android.content.Context;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Risky57 on 2017/4/21.
 */

public class TokenInterceptor implements Interceptor {

    private Context mContext;

    public TokenInterceptor (Context context) {
        mContext = context;
    }

    @Override
    public Response intercept (Chain chain) throws IOException {

        Request request = chain.request();
        if (!request.url().toString().endsWith("/login")) {
            String token = TokenUtil.getToken(mContext);
            request = request.newBuilder().header("token", token).build();
        }
        Response response = chain.proceed(request);

        if (response.code() == 404) {
            // 重新获取一下token
            refreshToken();
            String newToken = TokenUtil.getToken(mContext);
            request = request.newBuilder()
                    .header("token", newToken)
                    .build();
            response = chain.proceed(request);
        }

        return response;
    }

    private void refreshToken () throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        RequestBody body = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .url("http://localhost:8080/v1/author/token")
                .put(body)
                .build();
        Response response = client.newCall(request).execute();
        String newToken = response.body().string().trim();
        TokenUtil.saveToken(mContext, newToken);
    }
}
